package com.yesun.task.pipeline.handler.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yesun.core.util.FileUtils;
import com.yesun.server.mdp.service.client.config.HttpConfig;
import com.yesun.server.mdp.service.client.impl.DefaultClient;
import com.yesun.server.mdp.service.client.impl.http.HttpRequestContext;
import com.yesun.server.mdp.service.client.impl.http.HttpResponseContext;
import com.yesun.server.mdp.service.client.utils.SpiderUtil;
import com.yesun.task.pipeline.common.Constant;
import com.yesun.task.pipeline.common.StockCode;
import com.yesun.task.pipeline.domain.dto.JobDto;
import com.yesun.task.pipeline.domain.dto.TaskDto;
import com.yesun.task.pipeline.handler.Executor;
import com.yesun.task.pipeline.handler.Handler;
import com.yesun.task.pipeline.handler.Loader;
import com.yesun.task.pipeline.worker.ParallelWorker;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.BlockingQueue;

//股东人数数据
@Slf4j
public class HolderHandler extends Handler {

    static DefaultClient client = new DefaultClient();
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    static SimpleDateFormat shortSdf = new SimpleDateFormat("yyyyMMdd");
    static String TODAY = shortSdf.format(Calendar.getInstance().getTime());

    public HolderHandler(JobDto jobDto) {
        super(jobDto);
    }

    @Override
    public Loader getLoader() {
        //实例化
        return new Loader() {
            @Override
            public void load(BlockingQueue queue) {
                log.info("加载股东人数采集子任务...");
                //实现资金流入子任务，插入到队列
                String[] arr = StockCode.STOCK_CODE.split(",");
                for(String code : arr) {
                    String url = "http://basic.10jqka.com.cn/mobile/"+code +"/holdern.html";
                    TaskDto taskDto = new TaskDto();
                    taskDto.setJobName(jobDto.getJobName());
                    taskDto.setName(code + "股东人数采集任务");
                    taskDto.setTag(Constant.JOB_TAG_HOLDER);

                    Map<String,String> map = new HashMap<>();
                    map.put("url", url);
                    map.put("code", code);
                    map.put("saveTo", "/df_holder/"+ shortSdf.format(new Date()) +"/"+code+".csv");//暂时只支持保存到磁盘
                    taskDto.setMap(map);


                    //加入MAP_TASK
                    ParallelWorker.MAP_TASK.put(taskDto.getName(), taskDto.getJobName());

                    queue.offer(taskDto);
                    log.info("添加子任务：" + taskDto.getName());
                }
            }
        };
    }

    @Override
    public Executor getExecutor() {
        return new Executor() {
            @Override
            public void execute(TaskDto taskDto) {
                //执行task的采集
                log.info("execute：" + taskDto.getName());
                HttpConfig config = new HttpConfig(taskDto.getMap().get("url"), HttpConfig.HTTP_METHOD_GET);
                config.setEnctype("");
                config.setEncoding("UTF-8");
                HttpRequestContext request = new HttpRequestContext(config);
                try {
                    HttpResponseContext response = (HttpResponseContext) client.execute(request);
                    String content = response.getContentAsString("UTF-8");
                    StringBuffer sb = new StringBuffer("采集日期,股票代码,报告期,股东数量,股价(不用),\n"); //股价最好从其他表获取
                    String year = SpiderUtil.getContentByRegex(content, "var lyear = \\[([^\\]]+)\\]", 1).replaceAll("\"","");
                    String holder = SpiderUtil.getContentByRegex(content, "var lholder = \\[([^\\]]+)\\]", 1).replaceAll("\"","");
                    String price = SpiderUtil.getContentByRegex(content,"var lhold = \\[([^\\]]+)\\]",  1).replaceAll("\"","");

                    String[] arrYear = year.split(",");
                    String[] arrHolder = holder.split(",");
                    String[] arrPrice = price.split(",");
                    int i=0;
                    for(String y : arrYear) {
                        sb.append(TODAY + "," +taskDto.getMap().get("code") + "," + y + "," +arrHolder[i]+ "," +arrPrice[i]+ ",\n");
                        i++;
                    }
                    //log.info(sbResult.toString());
                    //save to
                    FileUtils.saveCsv(Constant.BASE_PATH + taskDto.getMap().get("saveTo"), sb.toString(), "UTF-8");
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }
}
